# -*- coding: utf-8 -*-
# @Time        :2025/8/22 16:12
# @Author      :文刀水寿
# @File        : until.py
"""
 @Description :
"""
from App.independent_records import process_independent_records
from Browser.views import *
import logging
from feishu.feishu_bitable import FeishuBiTable
from django.conf import settings
from Browser.views import browser_process

logger = logging.getLogger(__name__)


def update_feishu_tables():
    """
    核心函数：更新飞书表格数据
    既可以被定时任务调用，也可以被接口调用
    """
    try:
        table_id3 = settings.TABLE_ID3
        table_id4 = settings.TABLE_ID4
        app_token = settings.APP_TOKEN

        # 初始化飞书操作类
        feishu_bitable = FeishuBiTable(
            app_config=settings.FEISHU_APP_CONFIGS,
            app_token=app_token
        )

        # 获取两个表格的记录
        result3 = feishu_bitable.get_batch_records(table_id=table_id3)
        records3 = result3.get('data', {}).get('items', [])
        result4 = feishu_bitable.get_batch_records(table_id=table_id4)
        records4 = result4.get('data', {}).get('items', [])
        updated_records3 = []
        updated_records4 = []
        number = int(len(records3)) + 1

        if not records3 and records4:
            return JsonResponse({
                "code": 200,
                "message": "没有找到记录",
                "data": []
            })
        for i in range(1, number):
            updated_records3 = process_independent_records(
                records=records3,
                target_table_id=table_id3,
                feishu_bitable=feishu_bitable
            )

            updated_records4 = process_independent_records(
                records=records4,
                target_table_id=table_id4,
                feishu_bitable=feishu_bitable
            )
            i += 1

        return {
            "success": True,
            "data": {
                "table3": updated_records3,
                "table4": updated_records4
            }
        }

    except Exception as e:
        logger.error(f"更新失败：{str(e)}", exc_info=True)
        return {
            "success": False,
            "error": str(e)
        }
